package com.panda.pandawash.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.panda.pandawash.bean.BindDevicesBean;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.panda.pandawash.R;
import com.panda.pandawash.adapter.LeDeviceListAdapter;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.view.LoadingDialog;
import com.panda.pandawash.view.StatusBarCompat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by gaowf on 2017/2/24.
 */

public class DeviceScanActivity extends Activity implements LeDeviceListAdapter.MyCallback, View.OnClickListener {
	private static final String TAG = "DeviceScanActivity";

    private LeDeviceListAdapter mLeDeviceListAdapter;
	private ListView deviceList;
    private BluetoothAdapter mBluetoothAdapter;
    private static final int REQUEST_ENABLE_BT = 1;
    private boolean mScanning;
	/**
	 * 设备扫描时间降低到20秒
	 */
	private static final long SCAN_PERIOD = 2000;
	/**
	 * 加载的dialog
	 */
    private LoadingDialog dialog;
    private Handler mHandler;
	/**
	 *设备model name,获取不到
	 */
    private int deviceModel;
    private List<BindDevicesBean> myDevicesList;

	/**
	 * 返回键
	 */
	private ImageView mBack;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.device_scan_main);

        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) {
            StatusBarCompat.compat(this, getResources().getColor(R.color.colorPrimary));
        }

        deviceList = (ListView) findViewById(R.id.listView_devices);
		mBack = (ImageView) findViewById(R.id.btn_about_return);

		deviceList.setOnItemClickListener(mListOnClickListener);
		mBack.setOnClickListener(this);

		mHandler = new Handler();

		final BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		// Checks if Bluetooth is supported on the device.
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
			finish();
			return;
		}

		Intent myIntent = getIntent();
		deviceModel = myIntent.getIntExtra(MotorMonitorActivity.EXTRAS_DEVICE_MODEL, 0);

    }

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!mBluetoothAdapter.isEnabled()) {
			if (!mBluetoothAdapter.isEnabled()) {
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}
		}
		mLeDeviceListAdapter = new LeDeviceListAdapter(this, this, null, null);
		deviceList.setAdapter(mLeDeviceListAdapter);

		//scanLeDevice(true);
		if (dialog != null) {
			dialog.cancel();
		}
		dialog = new LoadingDialog(this, "正在搜索设备。。。");
		dialog.setCancelable(false);
		dialog.show();
		startScanTimer();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mScanning)
			//scanLeDevice(false);
			stopScanTimer();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mScanning) {
			//scanLeDevice(false);
			stopScanTimer();
		}
		finish();//灭屏时应该退出该界面
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mScanning)
			//scanLeDevice(false);
			stopScanTimer();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.device_scan, menu);//加载menu文件到布局
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		menu.clear();
		if (!mScanning) {
			menu.findItem(R.id.menu_stop).setVisible(false);
			menu.findItem(R.id.menu_scan).setVisible(true);
		} else {
			menu.findItem(R.id.menu_stop).setVisible(true);
			menu.findItem(R.id.menu_scan).setVisible(false);

		}
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_scan:
				startScanTimer();
				break;
			case R.id.menu_stop:
				stopScanTimer();
				break;
		}
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
			this.finish();
			return;
		}

	}

	private int TimerStep;
	private Timer mTimer;

	private TimerTask mTimerTask;

	private void startScanTimer() {
		mTimerTask = new TimerTask() {
			public void run() {
				++TimerStep;

				if ((TimerStep % 4) == 1) {
					mUIHandler.sendEmptyMessage(1);
				}
				else if ((TimerStep % 4) == 0) {
					mUIHandler.sendEmptyMessage(2);
				}
				else if (TimerStep >= 20){
					mUIHandler.sendEmptyMessage(3);
				}
			}
		};

		if (mTimer != null) {
			mTimer.cancel();
		}

		mTimer = new Timer();
		mTimer.schedule(mTimerTask, 500, 500);
	}

	private Handler mUIHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:
					mScanning = true;
					boolean scanRs = mBluetoothAdapter.startLeScan(mLeScanCallback);
					Log.i(TAG, "startLeScan--2--scanRs is " + scanRs);
					break;

				case 2:
					mScanning = false;
					mHandler.removeCallbacksAndMessages(null);
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					Log.i(TAG, "stopLeScan--4--");
					break;

				case 3:
					stopScanTimer();
					break;
			}				
		}
	};



	private void stopScanTimer() {
		mScanning = false;
		mHandler.removeCallbacksAndMessages(null);
		mBluetoothAdapter.stopLeScan(mLeScanCallback);
		Log.i(TAG, "stopLeScan--5--");

		if (dialog != null) {
			dialog.cancel();
			int deviceNum = (deviceList.getLastVisiblePosition()-deviceList.getFirstVisiblePosition()+1);
			if (deviceNum == 0) {
				showNoDeviceDialog();
			}

			dialog = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}
	private AlertDialog noDeviceDialog;
	private void showNoDeviceDialog() {
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.no_useful_device_dialog, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.NoUsefulDeviceDialogStyle);
		builder.setView(view);
		noDeviceDialog = builder.create();
		noDeviceDialog.setCancelable(false);
		noDeviceDialog.show();
		noDeviceDialog.getWindow().setContentView(R.layout.no_useful_device_dialog);
		noDeviceDialog.getWindow().findViewById(R.id.no_useful_device_btn)
				.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});
	}

	@SuppressLint("NewApi")
	private void scanLeDevice(final boolean enable) {
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {
				@SuppressLint("NewApi")
				@Override
				public void run() {
					mScanning = false;
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					Log.i(TAG, "stopLeScan--2--");
					if (dialog != null) {
						dialog.cancel();
						dialog = null;
					}
				}
			}, SCAN_PERIOD);

			mScanning = true;

			if (dialog != null) {
				dialog.cancel();
			}
			dialog = new LoadingDialog(this, "正在搜索设备。。。");
			dialog.show();
			boolean scanRs = mBluetoothAdapter.startLeScan(mLeScanCallback);
			Log.i(TAG, "startLeScan--1--scanRs is " + scanRs);
		} else {
			mScanning = false;
			mHandler.removeCallbacksAndMessages(null);
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
			Log.i(TAG, "stopLeScan--1--");
			if (dialog != null) {
				dialog.cancel();
				dialog = null;
			}
		}

    }

    LinearLayout layout;
    EditText updateName;

	AdapterView.OnItemClickListener mListOnClickListener = new OnItemClickListener() {

		@SuppressLint("NewApi")
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// TODO Auto-generated method stub
			Log.i(TAG, "ListOnClickListener position = " + position);
			TextView nameTextView = (TextView) view.findViewById(R.id.device_name);

			TextView addrTextView = (TextView) view.findViewById(R.id.device_address);

			Log.i(TAG, "name = " + nameTextView.getText().toString() + "  addr: " + addrTextView.getText().toString());

            final Intent intent = new Intent(DeviceScanActivity.this, MotorMonitorActivity.class);
            intent.putExtra(MotorMonitorActivity.EXTRAS_DEVICE_NAME, nameTextView.getText().toString());
            intent.putExtra(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS, addrTextView.getText().toString());
            intent.putExtra(MotorMonitorActivity.EXTRAS_DEVICE_MODEL, deviceModel);

            if (mScanning) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
				Log.i(TAG, "stopLeScan--3--");
                mScanning = false;
            }

			startActivity(intent);
			finish();
		}
	};

    @SuppressLint("NewApi")
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			// TODO Auto-generated method stub
			Log.i(TAG, "onLeScan--1--device is " + device + ", rssi is " + rssi);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					boolean flg = true;

                    for (Map<String, Object> devicemap : mLeDeviceListAdapter.updateDevicesList) {

                        String str1 = devicemap.get("devices_address").toString();
                        String str2 = device.getAddress();

                        if (str2.equals(str1)) {
                            flg = false;
                            return;
                        }
                    }
                    if (flg) {

                        if (device.getName() == null)
                            return;
                        Log.i("dennis123", "ADD_ADDRESS	" + device.getAddress() + "ADD_NAME  " + device.getName());

                        if (device.getName().equals("Motor Monitor")) {
                            Map<String, Object> map = new HashMap<String, Object>();

                            DbUtils dbUtils = CDApplication.getIntance().getDbUtil();
                            try {
                                myDevicesList = dbUtils.findAll(BindDevicesBean.class);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                            boolean bindstatus = false;
                            if (myDevicesList != null && myDevicesList.size() > 0) {
                                for (int i = 0; i < myDevicesList.size(); i++) {
                                    if (myDevicesList.get(i).getMacAddress() != null && !myDevicesList.get(i).getMacAddress().equals("")
                                            && myDevicesList.get(i).getMacAddress().equals(device.getAddress())) {
                                        bindstatus = true;
                                        return;
                                    }
                                }
                            }

                            map.put("devices_name", device.getName());
                            map.put("devices_address", device.getAddress());
                            map.put("device_bind_status", bindstatus);
                            mLeDeviceListAdapter.addDevice(map);
                            mLeDeviceListAdapter.notifyDataSetChanged();
                        }
                        Log.d("dennis123", "ADD_ADDRESS	" + device.getAddress() + "+++++++++++ end" + flg);
                        Log.d("dennis123", "ADD_NAME	" + device.getName());

                    }
                }
            });
        }
    };

    public int getDeviceNums() {

        return mLeDeviceListAdapter.getCount();
    }

	/**
	 * Le adapter的回调事件
	 * @param v
	 */
	@Override
    public void click(View v) {
        // TODO Auto-generated method stub
        Log.i("bear_", "id = " + v.getTag());

        mLeDeviceListAdapter.updateDeviceName((Integer) v.getTag(), updateName.getText().toString());
        // mLeDeviceListAdapter.notifyDataSetChanged();

        mLeDeviceListAdapter = new LeDeviceListAdapter(this, this, mLeDeviceListAdapter.devicesList, null);
        deviceList.setAdapter(mLeDeviceListAdapter);

    }

	/**
	 * 返回键的点击事件
	 * @param v
	 */

	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.btn_about_return:
				finish();
				break;
		}
	}
}

